package com.ericsson.common.util;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author wangjingshi
 * @description
 * @date 2020/9/10
 */
@Component
@Setter
@Getter
public class SocketClient {

    private String host;
    private int port;
    private Socket socket;
    private OutputStream outputStream;

    public Socket initSocket(String host,int port) throws IOException {
        socket = new Socket(host,port);
        socket.bind(new InetSocketAddress(9999));
        return socket;
    }

    public String sendMessage(String message) throws Exception{
        // 建立连接后获得输出流
        outputStream = socket.getOutputStream();
        //首先需要计算得知消息的长度
        byte[] sendBytes = message.getBytes("UTF-8");
        //然后将消息的长度优先发送出去
        outputStream.write(sendBytes.length >>8);
        outputStream.write(sendBytes.length);
        //然后将消息再次发送出去
        outputStream.write(sendBytes);
        outputStream.flush();
        socket.shutdownOutput();
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            // 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
            sb.append(new String(bytes, 0, len, "UTF-8"));
        }
        outputStream.close();
        inputStream.close();
        socket.close();
        return sb.toString().split(":")[1];
    }

    public void close() throws Exception{
        outputStream.close();
        socket.close();
    }

}
